<template>
  <div class="content">
    <!-- 顶部搜索栏 -->
    <div class="top">
      <a-card :bordered="false">
        <a-space :size="size">
          <a-input-search
            v-model:value="noticeDto.title"
            style="width: 250px"
            placeholder="请输入公告主题"
            size="large"
            @search="onSearch"
          >
            <template #enterButton>
              <a-button style="background-color: #409eff; color: white"
                >搜索</a-button
              >
            </template>
          </a-input-search>
          <a-button type="primary" @click="resetParamr" ghost
            ><ReloadOutlined />重置</a-button
          >
          <a-button type="primary" @click="showModal" ghost
            ><PlusCircleOutlined />新增</a-button
          >
          <a-popconfirm
            title="确认删除？"
            ok-text="确认"
            cancel-text="取消"
            @confirm="removeBachById"
            @cancel="cancel"
          >
            <a-button :disabled="!hasSelected" type="primary" danger ghost
              ><DeleteOutlined />批量删除</a-button
            >
          </a-popconfirm>
        </a-space>
      </a-card>
    </div>

    <!-- 表格数据展示 -->
    <div class="table">
      <a-card :bordered="false">
        <div>
          <a-table
            :row-selection="{
              selectedRowKeys: state.selectedRowKeys,
              onChange: onSelectChange,
            }"
            :data-source="data"
            :pagination="false"
            :loading="loading"
          >
            <a-table-column width="180px" key="title" title="主题" data-index="title">
            </a-table-column>
            <a-table-column
              :ellipsis="true"
              key="content"
              title="内容"
              data-index="content"
              width="400px"
            />
            <a-table-column
              width="180px"
              key="flag"
              title="所属"
              data-index="flag"
            >
              <template #default="{ record }">
                <a-tag
                  style="font-size: 14px"
                  :color="record.flag === '前台' ? 'pink' : 'green'"
                  >{{ record.flag }}</a-tag
                >
              </template>
            </a-table-column>
            <a-table-column
              width="180px"
              key="status"
              title="状态"
              data-index="status"
            >
              <template #default="{ record }">
                <a-tag
                  :color="record.status === 1 ? 'green' : 'red'"
                  style="font-size: 14px"
                  v-text="record.status === 1 ? '已发布' : '未发布'"
                ></a-tag>
              </template>
            </a-table-column>
            <a-table-column width="240px" key="id" title="操作">
              <template #default="{ record }">
                <div style="display: flex">
                  <div>
                    <a-button @click="edit(record.id)" type="link" ghost
                      >修改</a-button
                    >
                  </div>
                  <div style="margin-left: 10px">
                    <a-popconfirm
                      title="确认删除？"
                      ok-text="确认"
                      cancel-text="取消"
                      @confirm="remove(record.id)"
                      @cancel="cancel"
                    >
                      <a-button type="link" ghost danger> 删除 </a-button>
                    </a-popconfirm>
                  </div>
                </div>
              </template>
            </a-table-column>
          </a-table>
        </div>
        <!-- 分页 -->
        <div
          style="
            height: 40px;
            width: 100%;
            margin-top: 30px;
            display: flex;
            justify-content: center;
          "
        >
          <a-pagination
            v-model:current="pageNo"
            v-model:page-size="pageSize"
            :total="total"
            @change="handlePageChange"
            :show-total="(total) => `共 ${total} 条`"
          />
        </div>
      </a-card>
    </div>

    <!-- 新增弹出框 -->
    <div>
      <a-modal
        v-model:open="open"
        @cancel="handleCancel"
        title="新增公告"
        :footer="null"
      >
        <div style="padding: 30px 0 20px 50px">
          <a-form
            ref="formRef"
            :model="notice"
            :rules="rules"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-form-item ref="title" label="主题" name="title">
              <a-input
                maxlength="10"
                v-model:value="notice.title"
                size="large"
              />
            </a-form-item>
            <a-form-item ref="flag" label="所属" name="flag">
              <a-radio-group v-model:value="notice.flag">
                <a-radio value="前台">前台</a-radio>
                <a-radio value="后台">后台</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item ref="noticeStatus" label="发布" name="noticeStatus">
              <a-switch v-model:checked="notice.noticeStatus" />
            </a-form-item>
            <a-form-item ref="content" label="内容" name="content">
              <a-textarea
                size="large"
                v-model:value="notice.content"
                :rows="4"
                maxlength="58"
                placeholder="最多输入58个字符"
              />
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
              <a-button type="primary" @click="save">保存</a-button>
              <a-button style="margin-left: 10px" @click="handleCancel"
                >取消</a-button
              >
            </a-form-item>
          </a-form>
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script setup>
import {
  ReloadOutlined,
  PlusCircleOutlined,
  DeleteOutlined,
} from "@ant-design/icons-vue";
import { ref, reactive, computed, onMounted } from "vue";
import { message } from "ant-design-vue";
import {
  saveNotice,
  list,
  removeBatchByKeys,
  echo,
  update,
} from "@/api/notice";

const size = ref(20);
const total = ref(0);
const pageNo = ref(1);
const pageSize = ref(10);
const data = ref([]);
const notice = ref({
  key: null,
  title: "",
  flag: "",
  noticeStatus: false,
  content: "",
});

const loading = ref(true);
onMounted(() => {
  setInterval(() => {
    loading.value = false;
  }, 1000);
  getNotices();
});

//根据用户名进行模糊查询,没办法参数必须是一个对象
const noticeDto = ref({
  title: "",
});
//异步请求管理员数据
function getNotices() {
  list(pageNo.value, pageSize.value, noticeDto.value).then((res) => {
    if (res.code === 200 && res.data.data != null) {
      data.value = res.data.data;
      total.value = res.data.total;
    }
  });
}

//管理员数据模糊查询
function onSearch(searchValue) {
  noticeDto.value.title = searchValue;
  getNotices();
}

//重置模糊查询数据
function resetParamr() {
  noticeDto.value.title = "";
  getNotices();
}

//监听分页变化
function handlePageChange(param1, param2) {
  pageNo.value = param1;
  pageSize.value = param2;
  loading.value = true;
  setInterval(() => {
    loading.value = false;
  }, 1000);
  getNotices();
}

//新增管理员弹框
const open = ref(false);
const showModal = () => {
  open.value = true;
};

//新增管理员操作
function save() {
  formRef.value
    .validate()
    .then(() => {
      //新增管理员
      if (notice.value.key === null) {
        console.log(notice.value);
        saveNotice(notice.value).then((res) => {
          if (res.code === 200) {
            message.success("新增成功！");
            //重新加载管理员数据
            getNotices();
            open.value = false;
            notice.value = {};
            notice.value.key = null;
          }
        });
      } else {
        //修改管理员
        update(notice.value).then((res) => {
          if (res.code === 200) {
            message.success("修改成功！");
            //重新加载管理员数据
            getNotices();
            open.value = false;
            notice.value = {};
            notice.value.key = null;
          }
        });
      }
    })
    .catch((error) => {
      console.log("error", error);
    });
}

//取消新增管理员操作
function handleCancel() {
  open.value = false;
  notice.value = {};
  notice.value.key = null;
}

//管理员修改操作
function edit(id) {
  echo(id).then((res) => {
    if (res.code === 200 && res.data != null) {
      notice.value = res.data;
      open.value = true;
    }
  });
}

//管理员确认删除回调操作
function remove(id) {
  removeBatchByKeys(id).then((res) => {
    if (res.code === 200) {
      message.success("删除成功！");
      //重新加载分页数据
      getNotices();
    }
  });
}

//管理员取消删除回调操作
function cancel() {
  message.warning("取消删除！");
}

//数据校验
const formRef = ref();
const labelCol = {
  span: 5,
};
const wrapperCol = {
  span: 13,
};
const rules = {
  title: [
    {
      required: true,
      message: "请输入公告主题",
      trigger: "change",
    },
    {
      min: 4,
      max: 10,
      message: "长度为4~10个字符",
      trigger: "blur",
    },
  ],
  flag: [
    {
      required: true,
      message: "请选择公告所属前台或后台",
      trigger: "blur",
    },
  ],
  content: [
    {
      required: true,
      message: "请输入公告内容",
      trigger: "blur",
    },
  ],
};

//存储批量管理员id
const state = reactive({
  selectedRowKeys: [],
});
//当有一个或多个管理员被选中时触发按钮
const hasSelected = computed(() => state.selectedRowKeys.length > 0);
//批量删除管理员
const removeBachById = () => {
  setTimeout(() => {
    state.selectedRowKeys = [];
  }, 1000);
  //删除后做操作
  removeBatchByKeys(state.selectedRowKeys).then((res) => {
    if (res.code === 200) {
      message.success("删除成功！");
      //重新加载分页数据
      getNotices();
    }
  });
};
//当选中行改变时触发
const onSelectChange = (selectedRowKeys) => {
  state.selectedRowKeys = selectedRowKeys;
};
</script>

<style scoped>
.options {
  margin-top: 10px;
}

.table {
  margin-top: 10px;
}

.avatar-uploader > .ant-upload {
  width: 50px;
  height: 50px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
:deep(.ant-card-body) {
  padding: 10px;
}
</style>>
